
window.bab = {
	initFunctions: [],
	addInitFunction: function (f) {
		this.initFunctions.push(f);
	},
	init: function (domNode) {
		for (var i = 0; i < this.initFunctions.length; i++) {
			var initFunction = this.initFunctions[i];
			initFunction(domNode);
		}		
	}
};

jQuery(document).ready(function() {
	
	// All initialization function should be added to the window.bab object
	// using the addInitFunction method.
	// Init function should take a dom element as parameter.
	
	var body = document.getElementsByTagName("BODY")[0];
	window.bab.init(body);
});






function widget_datePickerInit(domNode)
{
	if (jQuery.datepicker) {
		// Prepare datepicker widgets
		jQuery(domNode).find(".widget-datepicker").each(function() {
			var meta = window.babAddonWidgets.getMetadata(this.id);
			var datePickerOptions = {
				yearRange: '1900:2100',
				firstDay: 1,
				hideIfNoPrevNext: true, 
				constrainInput: true,
				numberOfMonths: meta.numberOfMonths,
				dateFormat: 
					meta.format
					.replace('%Y', 'yy')
					.replace('%m', 'mm')
					.replace('%d', 'dd'), 
				duration: 0, 
				beforeShow: function() {
					var meta = window.babAddonWidgets.getMetadata(this.id);
					if (meta.mindatey != null) {
						mindate = new Date();
						mindate.setYear(meta.mindatey);
						mindate.setMonth(meta.mindatem -1);
						mindate.setDate(meta.mindated);
					} else {
						mindate = null;
					}
					if (meta.maxdatey != null) {
						maxdate = new Date();
						maxdate.setYear(meta.maxdatey);
						maxdate.setMonth(meta.maxdatem -1);
						maxdate.setDate(meta.maxdated);
					} else {
						maxdate = null;
					}

					return {
							minDate: mindate==null ? meta.from	? jQuery('#'+meta.from).datepicker("getDate") 	: null : mindate,
							maxDate: maxdate==null ? meta.to	? jQuery('#'+meta.to).datepicker("getDate") 	: null : maxdate
					};
					
				}
			};
			if (meta.dateClickUrl != '') {
				datePickerOptions.onSelect = function(dateText, inst) {
					var dateClickUrl = meta.dateClickUrl.replace('__date__', dateText);
					window.location.href = dateClickUrl;
				};
			}
			if (jQuery(this).hasClass('widget-datepicker-changeyear')) {
				datePickerOptions.changeYear = true;
			}
			if (jQuery(this).hasClass('widget-datepicker-changemonth')) {
				datePickerOptions.changeMonth = true;
			}

			jQuery(this)
				.datepicker(datePickerOptions)
				.attr('autocomplete', 'off');
		});
	}
	
}






jQuery.fn.limitMaxLength = function(options){

	var settings = jQuery.extend({
		attribute: "maxlength",
		onLimit: function(){},
		onEdit: function(){}
	}, options);

	// Event handler to limit the textarea
	var onEdit = function(){
		var textarea = jQuery(this);
		var maxlength = parseInt(textarea.attr(settings.attribute));

		if(textarea.val().length > maxlength){
			textarea.val(textarea.val().substr(0, maxlength));

			// Call the onlimit handler within the scope of the textarea
			jQuery.proxy(settings.onLimit, this)();
		}

		// Call the onEdit handler within the scope of the textarea
		jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
	}

	this.each(onEdit);

	return this.keyup(onEdit)
				.keydown(onEdit)
				.focus(onEdit)
				.live('input paste', onEdit);
}



/*
 * jQuery autoResize (textarea auto-resizer)
 * @copyright James Padolsey http://james.padolsey.com
 * @version 1.04
 */

jQuery.fn.autoResize = function(options) {
        
    // Just some abstracted details,
    // to make plugin users happy:
    var settings = jQuery.extend({
        onResize : function(){},
        animate : false,
        animateDuration : 150,
        animateCallback : function(){},
        extraSpace : 22,
        limit: 1000
    }, options);
    
    // Only textarea's auto-resize:
    this.filter('textarea').each(function(){
        
            // Get rid of scrollbars and disable WebKit resizing:
        var textarea = jQuery(this).css({resize:'none','overflow-y':'hidden'}),
        
            // Cache original height, for use later:
            origHeight = 0; //textarea.height(),
            
            // Need clone of textarea, hidden off screen:
            clone = (function(){
                
                // Properties which may effect space taken up by chracters:
                var props = ['height','width','lineHeight','textDecoration','letterSpacing'],
                    propOb = {};
                    
                // Create object of styles to apply:
                $.each(props, function(i, prop){
                    propOb[prop] = textarea.css(prop);
                });
                
                // Clone the actual textarea removing unique properties
                // and insert before original textarea:
                return textarea.clone().removeAttr('id').removeAttr('name').css({
                    position: 'absolute',
                    top: 0,
                    left: -9999,
                    minHeight: 0
                }).css(propOb).attr('tabIndex','-1').insertBefore(textarea);
				
            })(),
            lastScrollTop = null,
            updateSize = function() {
				
                // Prepare the clone:
                clone.height(0).val(jQuery(this).val()).scrollTop(10000);
				
                // Find the height of text:
                var scrollTop = Math.max(clone.scrollTop(), origHeight) + settings.extraSpace,
                    toChange = $(this).add(clone);
					
                // Don't do anything if scrollTip hasen't changed:
                if (lastScrollTop === scrollTop) { return; }
                lastScrollTop = scrollTop;
				
                // Check for limit:
                if ( scrollTop >= settings.limit ) {
                    $(this).css('overflow-y','');
                    return;
                }
                // Fire off callback:
                settings.onResize.call(this);
				
                // Either animate or directly apply height:
                settings.animate && textarea.css('display') === 'block' ?
                    toChange.stop().animate({height:scrollTop}, settings.animateDuration, settings.animateCallback)
                    : toChange.height(scrollTop);
            };
        
        // Bind namespaced handlers to appropriate events:
        textarea
            .unbind('.dynSiz')
            .bind('keyup.dynSiz', updateSize)
            .bind('change.dynSiz', updateSize)
        	.bind('resize', updateSize);
        
        textarea.trigger('resize');
        
    });
    
    // Chain:
    return this;
};




function widget_baseInit(domNode) {

	// Prepare tab widgets
	if (jQuery().tabs) {
		jQuery(domNode).find(".widget-tabs").not('.widget-static-tabs').each(function() {
			
			var myFile = document.location.toString();
			if (myFile.match('#') && !jQuery(this).find('.widget-tab-selected').get(0)) {
				var tabid = myFile.split('#')[1];
				jQuery(this).find('a[href=#'+tabid+']').parent().addClass('widget-tab-selected');
			}
			
			var selectedTabNumber = 0;
			var tagNumber = 0;
			jQuery(this).find('.widget-tab').each(function() {
				if (jQuery(this).hasClass('widget-tab-selected')) {
					selectedTabNumber = tagNumber;
				}
				tagNumber++;
			}
			);
			jQuery(this).tabs({ selected: selectedTabNumber });
		}
		);
	}

	if (jQuery().accordion) {
		// Prepare accordions widgets
		jQuery(domNode).find(".widget-accordions").each(function () {
			
			var meta = window.babAddonWidgets.getMetadata(this.id);

			var accordionOptions = {
				header: "span.widget-accordion-header",
				navigation: true,
				autoHeight: false,
				active: false,
				clearStyle: true,
				collapsible: true,
				active: ".widget-accordion-header-open"
			};
			if (!meta.animated) {
				accordionOptions.animated = false;
			}
			if (meta.collapsible == false) {
				accordionOptions.collapsible = false;
			}
			jQuery(this)
				.accordion(accordionOptions);
		});
	}


	// popup links
	jQuery(domNode).find("a.widget-popup").click(function(e) {
		bab_popup(jQuery(this).attr('href'));
		e.stopPropagation();
		return false;
	});


	jQuery(domNode).find(".widget-confirm").click(function(e) {
		try {
			if (confirmationMessage = window.babAddonWidgets.getMetadata(this.id).confirmationMessage) {
				if (!window.confirm(confirmationMessage)) {
					e.stopPropagation();
					return false;
				}
			}
			return true;
		} catch (e) {
			return true;
		}
	});
	
	
	// sortable
	if (jQuery().sortable) {
		jQuery(domNode).find(".widget-sortable").sortable({
			placeholder: 'widget-sortable-placeholder'
		});
	}

	
	jQuery(domNode).find(".widget-filter .header").click(function(e) {
		var filter = jQuery(this).parents('.widget-filter').get(0);
		form = jQuery(filter).find('form.widget-form').get(0);
		jQuery(form).toggle('normal');
	});


	jQuery(domNode).find('.widget-textedit').each(function () {
		var meta = window.babAddonWidgets.getMetadata(this.id);
		if (meta && meta.maxSize) {
			jQuery(this).attr('maxlength', meta.maxSize);
			jQuery(this).limitMaxLength({});
		}
	});

	jQuery(domNode).find('.widget-textedit.widget-autoresize').autoResize();

	
	
	// associated displayable widgets
	
	jQuery(domNode).find('.widget-associated-displayable').each(function(key, source) {
		
		source = jQuery(source);
		var metadata = window.babAddonWidgets.getMetadata(source.attr('id'));
		
		if (metadata.displayable)
		{
			var eventAction = function() {
				
				var source = jQuery(this);
				
				switch(true)
				{
					case source.is('select'):
						var selected = source.find('option:selected').attr('value');
						break;
					
					case source.is('input[type="checkbox"]:checked'):
						var selected = source.attr('value');
						break;
						
					case source.is('input[type="checkbox"]'):
						var selected = jQuery('input[type="hidden"][name="'+source.attr('name')+'"]').attr('value');
						break;
				}
				
				for(var i =0; i< metadata.displayable.length; i++)
				{
					var target = jQuery('#'+metadata.displayable[i][0]);
					var values = metadata.displayable[i][1];
					var disp = 0;
	
					for (var j=0; j < values.length; j++)
					{
						if (values[j] == selected)
						{
							target.show();
							disp = 1;
							break;
						}
					}
					
					if (disp == 0)
					{
						target.hide();
					}
				}
			}
			
			source.change(eventAction);
			
			
			source.change();
		}
	});
}


window.bab.addInitFunction(widget_baseInit);

window.bab.addInitFunction(widget_datePickerInit);
